<template>
  <div>
    <el-button icon="el-icon-setting" type="primary" @click="initForm()">{{ $tt('label_pms_ref_warehouse_group_setting')
    }}</el-button>

    <el-dialog :title="$tt('label_pms_ref_warehouse_group_setting')" :visible.sync="dialogFormVisible" width="1000px"
      style="padding: 0px;">

      <el-button icon="el-icon-plus" @click="groupArr.push({
        name: $tt('label_group_name'),
        warehouses: [],
        showRemove: false
      })">{{ $tt('label_add_group') }}
      </el-button>

      <i class="el-icon-warning" style="margin-left: 10px;"></i> {{ $tt('tip_drag_wrehouse_adjust_group') }}

      <div class="wh-group-wrapper">

        <div class="wh-group-body" v-for="group, groupIndex in groupArr" @mouseover="group.showRemove = true"
          @mouseleave="group.showRemove = false" :key="groupIndex">
          <div class="wh-group-body-title">
            <el-input v-model="group.name">
              <template slot="prepend">{{ $tt('label_group') }} {{ groupIndex + 1 }}</template>
            </el-input>
          </div>

          <div class="wh-group-body-grid" :id="`${groupHead}___${groupIndex}`" :data-index="groupIndex"
            :ref="`group_${groupIndex}`">
            <div v-for="warehouse, warehouseIndex in group.warehouses " class="flex_center"
              :ref_warehouse_id="warehouse.warehouseId" :key="warehouse.warehouseId">
              <el-button icon="el-icon-caret-left" circle size="mini" v-show="groupIndex > 0" 
                @click="groupMove(`${groupHead}___${groupIndex}`,warehouseIndex,`${groupHead}___${groupIndex-1}`,0)"/>
              <div class="flex_cell wh-group-body-row ">{{ warehouse.warehouseName }}</div>
              <el-button icon="el-icon-caret-right" circle size="mini" v-show="groupIndex < groupArr.length - 1" 
              @click="groupMove(`${groupHead}___${groupIndex}`,warehouseIndex,`${groupHead}___${groupIndex+1}`,0)"/>
            </div>
          </div>

          <el-button v-show="group.showRemove" class="wh-group-body-remove" type="text" line icon="el-icon-close"
            @click="removeGroup(groupIndex)">{{ $tt('label_delete_group') }}
          </el-button>

        </div>

      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submitForm()">{{ $tt('label_confirm') }}</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>

import Sortable from 'sortablejs'
import { SlickList, SlickItem } from 'vue-slicksort'

export default {


  components: {
    SlickList, SlickItem
  },

  data() {

    return {

      idHead: 'id_' + Math.random(),

      groupHead: 'group_' + Math.random(),

      dialogFormVisible: false,

      dataMap: {},

      value: '',

      warehouseLoadDone: false,
      groupLoadDone: false,

      groupArr: [],
      warehouseArr: [],
      warehouseCache: {},
    }

  },

  watch: {

    'dialogFormVisible'(val, old) {
      if (val) {
        window.setTimeout(() => {
          this.initGroup()
        }, 200)
      }
    },

    'groupArr'(val, old) {
      if (this.dialogFormVisible) {
        this.initGroup()
      }
    }
  },

  created() {

    this.$ajax({
      url: '/fms-api/product/PmsWarehouseGroupRpc/selectAll.json',
      method: 'post',
      success: (res) => {
        if (res.data && res.data.rows) {
          let tmpArr = res.data.rows

          tmpArr.forEach(row => {
            row.showRemove = false
            if (!row.warehouses) {
              row.warehouses = []
            }
          })
          this.groupArr = tmpArr

        }

        this.groupLoadDone = true
        this.initFirst()
      }
    })

    this.$ajax({
      url: '/oms-api/base/OmsBaseWarehouseRpc/selectAllEnable.json',
      method: 'post',
      success: (res) => {
        if (res.data && res.data.rows) {
          this.warehouseArr = res.data.rows

          this.warehouseArr.forEach(wh => {
            this.warehouseCache[wh.id] = wh
          })

        }
        this.warehouseLoadDone = true
        this.initFirst()
      }
    })
  },

  mounted() {
  },

  methods: {

    initFirst() {
      let _this = this
      if (_this.groupLoadDone && _this.warehouseLoadDone) {


        _this.groupArr.forEach(group => {

          if (group.warehouses) {
            //  filter(wh => _this.warehouseCache[wh.warehouseId]).map
            group.warehouses.forEach(wh => {

              if (_this.warehouseCache[wh.warehouseId]) {
                wh.warehouseName = _this.warehouseCache[wh.warehouseId].name
                wh.warehouseCode = _this.warehouseCache[wh.warehouseId].code
              }
              else {
                // delete wh
              }
            })
          }
        })

        let leftWh = []
        forloop: for (let i = 0; i < _this.warehouseArr.length; i++) {

          let wh = _this.warehouseArr[i]
          for (let j = 0; j < _this.groupArr.length; j++) {

            let group = _this.groupArr[j]
            if (group.warehouses && group.warehouses.length > 0) {
              let warehouseIds = group.warehouses.map(kk => kk.warehouseId)
              if (warehouseIds.contains(wh.id)) {
                continue forloop
              }
            }
          }

          leftWh.push(wh)
        }

        // 从现有分组中删除已经不存在的仓库

        let allWhIds = _this.warehouseArr.map(e => e.id)
        _this.groupArr.forEach(group => {
          let indexArr = []
          for (let i = 0; i < group.warehouses.length; i++) {
            if (!allWhIds.contains(group.warehouses[i].warehouseId)) {
              indexArr.push(i)
            }
          }

          //
          for (let i = indexArr.length - 1; i >= 0; i--) {

            //
            group.warehouses.splice(indexArr[i], 1)
          }

        })


        if (leftWh.length > 0) {
          let tmpArr = leftWh.map(kk => {
            return { 'warehouseId': kk.id, 'warehouseName': kk.name }
          });
          _this.groupArr.push({
            name: '未分组',
            warehouses: tmpArr
          })
        }
      }
    },


    getGroupIndex(domId) {
      let index = domId.lastIndexOf('___')
      if (index != -1) {
        return parseInt(domId.substring(index + 3))
      }
      return -1
    },

    initGroup() {
      this.$nextTick(() => {

        for (let i = 0; i < this.groupArr.length; i++) {



          const _group = document.getElementById(this.groupHead + '___' + i)



          Sortable.create(_group, {
            setData: function () {
            },
            group: 'shared',
            animation: 150,
            onEnd: async (evt) => {

              this.groupMove(evt.from.id, evt.oldIndex, evt.to.id, evt.newIndex)
            }
          })
        }
      })
    },
    groupMove(formGroupId, oldIndex, toGroupId, newIndex) {
      let fromGroupIndex = this.getGroupIndex(formGroupId)
      let toGroupIndex = this.getGroupIndex(toGroupId)
      let old = this.groupArr[fromGroupIndex].warehouses[oldIndex]
      this.groupArr[fromGroupIndex].warehouses.splice(oldIndex, 1,)
      this.groupArr[toGroupIndex].warehouses.splice(newIndex, 0, old)
    },


    initForm() {
      this.dialogFormVisible = true
    },


    removeGroup(index) {

      let groups = this.groupArr

      if (groups.length <= 1) {
        return
      }

      if (groups[index].warehouses.length > 0) {

        groups[index].warehouses.forEach(e => {

          if (index == 0) {
            groups[1].warehouses.push(e)
          } else {
            groups[0].warehouses.push(e)
          }
        })
      }

      this.groupArr.splice(index, 1);

    },

    submitForm() {


      this.$ajax({
        url: '/fms-api/product/PmsWarehouseGroupRpc/saveUpdate.json',
        data: { 'json': JSON.stringify(this.groupArr) },
        success: (res) => {
          this.$message({
            type: 'success',
            message: this.$tt('tip_submit_success')
          })

          this.$emit('afterSubmit')

          this.dialogFormVisible = false

        }
      })

    }

  }
}
</script>
<style>
.wh-group-wrapper {
  display: flex;
  margin-top: 10px;
  flex-wrap: wrap;

}

.wh-group-wrapper .wh-group-body {
  display: flex;
  width: 220px;
  flex-direction: column;
  border: 1px dashed #DCDFE6;
  margin-right: 8px;
  border-radius: 4px;
  padding: 4px;
  position: relative;
  min-height: 120px;
  padding-bottom: 30px;
}

.wh-group-wrapper .wh-group-body .wh-group-body-title {
  height: 38px;
}

.wh-group-wrapper .wh-group-body .wh-group-body-grid {
  flex: 1;
  display: flex;
  flex-direction: column;
  text-align: center;
}

.wh-group-body-row {
  cursor: move;
  line-height: 38px;
}

.wh-group-body-remove {
  position: absolute;
  bottom: 0px;
  right: 8px;
  color: red;
}
</style>
